// utils/websocket.js
// import Vue from 'vue'

export  const WebSocketManager = {
  install(Vue) {
    // 创建WebSocket实例‌:ml-citation{ref="5,6" data="citationList"}
    Vue.prototype.$socket = {
      ws: null,
      isConnected: false,
      reconnectTimer: null,
      eventBus: new Vue(), // 用于事件派发‌:ml-citation{ref="7" data="citationList"}
      
      // 初始化连接‌:ml-citation{ref="8" data="citationList"}
      connect(url) {
        if (this.ws) return
        
        this.ws = new WebSocket(url)
              
        // 事件监听‌:ml-citation{ref="5,6" data="citationList"}
        this.ws.onopen = () => {
          console.log("ws open")
          this.isConnected = true
          this.eventBus.$emit('socket-connected')
        }
        
        this.ws.onmessage = (event) => {
          this.eventBus.$emit('socket-message', JSON.parse(event.data)) // 自动解析JSON‌:ml-citation{ref="5" data="citationList"}
        }
        
        this.ws.onerror = () => {
          console.log("ws error")
          this.isConnected = false
          this.eventBus.$emit('socket-disconnected')
          this.handleReconnect(url) // 自动重连‌:ml-citation{ref="4,8" data="citationList"}
        }

        this.ws.onclose = () => {
          console.log("ws close")
          this.isConnected = false
          this.eventBus.$emit('socket-disconnected')
          this.handleReconnect(url) // 自动重连‌:ml-citation{ref="4,8" data="citationList"}
        }
      },

      // 发送消息‌:ml-citation{ref="6,8" data="citationList"}
      send(data) {
        if (this.isConnected) {
          this.ws.send(JSON.stringify(data))
        }
      },

      // 关闭连接‌:ml-citation{ref="6,8" data="citationList"}
      disconnect() {
        if (this.ws) {
          this.ws.close()
          this.ws = null
          clearTimeout(this.reconnectTimer)
        }
      },

      // 自动重连逻辑‌:ml-citation{ref="4,8" data="citationList"}
      handleReconnect(url) {
        this.reconnectTimer = setTimeout(() => {
          this.connect(url)
        }, 5000)
      }
    }
  }
}

// export default WebSocketManager
// 全局注册‌:ml-citation{ref="7" data="citationList"}
// Vue.use(WebSocketManager)
